package main

import (
	"client/pb"
	"encoding/binary"
	"fmt"
	"io"
	"net"
	"packet"
)

func main() {
	println("客户端启动开始")

	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	checkError(err)
	defer conn.Close()

	fmt.Printf("客户端启动成功\n\n")

	roleLogin := pb.RoleLogin{Account: "admin", Password: "admin"}
	_, err = conn.Write(roleLogin.Encode())
	checkError(err)

	roleLogin2 := pb.RoleLogin{Account: "root", Password: "root", Remark: "备注", Video: []byte{66, 88, 99}}
	_, err = conn.Write(roleLogin2.Encode())
	checkError(err)

	for {
		headData := make([]byte, 2)
		_, err := io.ReadFull(conn, headData)
		checkError(err)

		bodyLen := binary.BigEndian.Uint16(headData)
		bodyData := make([]byte, bodyLen)
		_, err = io.ReadFull(conn, bodyData)
		checkError(err)

		dispatch(bodyData)
	}
}

func dispatch(bodyData []byte) {
	packetIdData := bodyData[:2]
	packetId := binary.BigEndian.Uint16(packetIdData)
	println("协议 ID:", packetId)

	packetData := bodyData[2:]
	packetInst := packet.NewReadBuff(packetData)

	switch packetId {
	case pb.PRoleLoginOk:
		roleLoginOk := pb.RoleLoginOkDecode(packetInst)
		fmt.Printf("登录成功:%v\n", roleLoginOk)
	case pb.PGoodsItem:
		goodsItem := pb.GoodsItemDecode(packetInst)
		fmt.Printf("物品数据:%v\n", goodsItem)
	default:
		fmt.Println("未知协议 ID:", packetId)
	}
}

func checkError(err error) {
	if err == nil {
		return
	}

	panic(fmt.Sprintf("checkError err:%s\n", err))
}
